import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Form, Switch, Checkbox, Input, Row, Col, Select, InputNumber, message, Button, Spin, Popover } from 'antd'
import { messages } from 'share/common';
import WrapFormItem from 'components/wrap-form-item';
import Priority from 'components/template/priority';
import Chooser from 'components/chooser';
import beepTimerService from 'containers/setting/beep-timer/beep-timer.service';
import 'styles/setting/beep-timer/slide-content/travel-content.scss';
const { Option } = Select;
const FormItem = Form.Item;
const CheckboxGroup = Checkbox.Group;
@Form.create()
@connect(mapStateToProps)

class TravelContent extends Component {

  state = {
    priority: this.props.info.id ? {
      levelCode: this.props.info.levelCode,
      levelOrgId: this.props.info.levelCode === 'SET_OF_BOOK' ? this.props.info.setOfBooksId : this.props.info.companyOID,
      levelOrgName: this.props.info.levelOrgName
    } : {
      levelCode: 'SET_OF_BOOK',
      levelOrgId: this.props.company.setOfBooksId,
      levelOrgName: this.props.company.setOfBooksName
    },
    saveLoading: false,
    honestLoading: false,
    honestInfo: {},
    loading: false,
    formOIDValues: this.props.info.id ? JSON.parse(this.props.info.params).formOIDs.map((formOID) => {
      return { formOID }}) : [],
    remindTypesOption:[
      {label: messages('basic-13.key104')/*APP消息*/, value: "APP"},
      {label: messages('basic-13.key105')/*邮件提醒*/, value: "EMAIL"},
    ]
  };

  selectorItem = {
    title: messages('basic-13.key246')/*申请单*/,
    url: `/api/custom/forms/loan/reference`,
    searchForm: [{
      type: 'input',
      id: 'formCode',
      label: messages('basic-13.key247')/*表单编码*/
    }, {
      type: 'input',
      id: 'formName',
      label: messages('basic-13.key248')/*表单名称*/,
    }],
    columns: [
      {
        title: messages('basic-13.key249')/*层级*/,
        dataIndex: 'fromTypeName',
        render: value => <Popover placement="topLeft" content={value}>{value}</Popover>
      },
      {
        title: messages('basic-13.key9')/*所属组织*/,
        dataIndex: this.state.priority && this.state.priority.levelCode && this.state.priority.levelCode === 'COMPANY' ? 'companyName' : 'setOfBooksName',
        render: value => <Popover placement="topLeft" content={value}>{value}</Popover>
      },
      {
        title: messages('basic-13.key248')/*表单名称*/,
        dataIndex: 'formName',
        render: value => <Popover placement="topLeft" content={value}>{value}</Popover>
      },
      {
        title: messages('basic-13.key247')/*表单编码*/,
        dataIndex: 'formCode',
        render: value => <Popover placement="topLeft" content={value}>{value}</Popover>
      }
    ],
    key: 'formOID'
  };

  componentDidMount() {
    const { id } = this.props.info;
    id && this.getHonestInfo(id);
  };

  handlePriority = value => {
    if (!value) {
      message.error(messages('basic-13.key220')/*请选择所属组织*/);
    };
    const priority = {
      levelOrgId: value && (value.companyOID || value.levelOrgId),
      levelCode: value && ( value.levelCode),
      levelOrgName: value && (value.levelOrgName)
    };
    this.props.form.setFieldsValue({'formOIDs': []});
    this.setState({ formOIDValues: [], priority });
  };

  handleSelectItems = value => {
    const selectedItems = value.map((item) => {
      return item.formOID;
    });
    const values = selectedItems.map((formOID, index) => {
      return { formOID }
    });
    this.setState({formOIDValues: values});
    this.props.form.setFieldsValue({'formOIDs': selectedItems});
  };

  getHonestInfo = id => {
    this.setState({ honestLoading: true });
    beepTimerService.getHonestList(id)
      .then(res => {
        this.setState({honestInfo: res.data.id ? res.data : {}})
      })
      .finally(() => this.setState({ honestLoading: false }))
  };

  handleSave = e => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      const { info } = this.props;
      const { levelCode = '', levelOrgId = '' } = this.state.priority;
      if (!err) {
        if (!this.state.priority || !levelOrgId) {
          message.error(messages('basic-13.key220')/*请选择所属组织*/);
          return;
        }
        if (!values.wrapTime.remindDay || !values.wrapTime.hour) {
          message.error(messages('basic-13.key250')/*请选择提醒时间*/);
          return;
        }
        this.setState({ loading: true });
        let params = {
          enabledFlag: values.enabledFlag,
          hour: Number(String(values.wrapTime.hour).split(':')[0]),
          code: 'TravelApplicationNoticeTask',
          levelCode: levelCode,
          params: JSON.stringify({
                    title: values.title,
                    content: values.content,
                    remindDay: values.wrapTime.remindDay,
                    remindTypes: values.remindTypes,
                    formOIDs: values.formOIDs
                  })
        };
        if (levelCode === 'SET_OF_BOOK') {
          params.setOfBooksId = levelOrgId;
        } else {
          params.companyOID = levelOrgId;
        };
        info.id && (params.id = info.id);
        beepTimerService.newBeepTimer(params).then(res => {
          const conditionId = values.conditionId && values.conditionId[0] && values.conditionId[0].id;
          beepTimerService.saveHonestInfo({ taskId: info.id || res.data.rows.id, conditionId })
            .then(() => {
              message.success(messages('common.save.success',{arg1: ""})/*{arg1} 保存成功*/);
              this.props.close(true);
            })
            .catch(e => errorMessage(e.response))
            .finally(() => this.setState({ loading: false }))
        }).catch(e => {
          this.setState({ loading: false });
          message.error(`${messages('common.save.filed')/*保存失败*/}，${e.response.data.message}`/*保存失败*/)
        })
      }
    })
  };

  render() {
    const { info } = this.props;
    const { priority, saveLoading, loading, remindTypesOption, formOIDValues, honestLoading, honestInfo } = this.state;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 10 },
      },
    };
    const paramsData = JSON.parse(info.params || '{}');
    let hourOption = [];
    for (let i = 0; i <= 23; i++) {
      hourOption.push(<Option value={i + ''}>{i + ":00"}</Option>)
    };
    let honestExtraParams = {taskConfigCode: 'TravelApplicationNoticeTask'};
    if (priority && priority.levelOrgId) {
      const paramName = priority.levelCode === 'SET_OF_BOOK' ? 'setOfBooksId' : 'companyId';
      honestExtraParams[paramName] = priority.levelOrgId;
    }

    return (
      <div>
        <Spin spinning={loading}>
          <Form className="new-form">
            <FormItem
              label={messages('common.column.status')/*状态*/}
              {...formItemLayout}
            >
              {getFieldDecorator("enabledFlag", {
                valuePropName: "checked",
                initialValue: info.id ? info.enabledFlag : true
              })(
                <Switch/>
              )}
            </FormItem>

            <Priority
              top='SET_OF_BOOK'
              onChange={this.handlePriority}
              formItemLayout={formItemLayout}
              defaultValue={priority}
              showCompanyComponent={false}
              disabled={!!info.id}
              required={true}
            />

            <h3 className='sub-title'>{messages('basic-13.key15')/*消息内容*/}</h3>
            <FormItem
              label={messages('basic-13.key16')/*消息标题*/}
              {...formItemLayout}
            >
              {getFieldDecorator("title", {
                rules: [{
                  required: true,
                  message: messages('common.can.not.be.empty',{arg1: messages('basic-13.key16')/*消息标题*/})/*{arg1} 不能为空*/
                }, {
                  max: 50,
                  message: messages('common.max.characters.length',{arg1: 50})/*最多输入{arg1}个字符*/
                }],
                initialValue: paramsData.title
              })(
                <Input placeholder={messages('basic-13.key251')/*出差结束提醒*/}/>
              )}
            </FormItem>
            <FormItem
              label={messages('basic-13.key17')/*消息正文*/}
              {...formItemLayout}
            >
              {getFieldDecorator('content', {
                rules: [{
                  required:true,
                  message: messages('common.can.not.be.empty',{arg1: messages('basic-13.key17')/*消息正文*/})/*{arg1} 不能为空*/
                }, {
                  max: 100,
                  message: messages('common.max.characters.length',{arg1: 100})/*最多输入{arg1}个字符*/
                }],
                initialValue: paramsData.content
              })(
                <Input.TextArea placeholder={messages('basic-13.key222')/*请及时报销*/}/>
              )}
            </FormItem>

            <h3 className='sub-title'>{messages('basic-13.key252')/*消息提醒*/}</h3>
            <FormItem
              label={messages('basic-13.key142')/*适用单据*/}
              {...formItemLayout}
            >
              {getFieldDecorator('formOIDs', {
                rules: [{
                  required: true,
                  message: messages('common.can.not.be.empty',{arg1: messages('basic-13.key142')/*适用单据*/})/*{arg1} 不能为空*/
                }],
                initialValue: info.id ? paramsData.formOIDs : []
              })(
                <Row gutter={10}>
                  <Col span={2}> 
                    {messages('basic-13.key253')/*表单: */}
                  </Col>
                  <Col span={12}>
                  <Chooser
                      selectorItem={this.selectorItem}
                      labelKey='formName'
                      valueKey='formOID'
                      disabled={!priority}
                      showNumber
                      showClear
                      onChange={value => this.handleSelectItems(value)}
                      value={formOIDValues}
                      listExtraParams = {priority && (priority.levelCode && priority.levelCode === 'COMPANY' ?
                                        {companyOID: priority.levelOrgId && priority.levelOrgId, setOfBooksId: '', formTypeList: [2001]} :
                                        {setOfBooksId: priority.levelOrgId && priority.levelOrgId, companyOID: '', formTypeList: [2001]})}/>
                  </Col>
                </Row>
              )}
            </FormItem>
            <FormItem
              label={messages('basic-13.key35')/*提醒时间*/}
              {...formItemLayout}
            >
              {getFieldDecorator('wrapTime', {
                rules: [{
                  required: true,
                  message: messages('common.can.not.be.empty',{arg1: messages('basic-13.key35')/*提醒时间*/})/*{arg1} 不能为空*/
                }],
                initialValue: { remindDay: info.id ? paramsData.remindDay : undefined, hour: info.hour + ":00"}
                })(
                  <WrapFormItem>
                    {(onChange, value) => (
                      <Row gutter={1}>
                        <Col span={14}>
                          {messages('basic-13.key138')/*发送日期*/}:&nbsp;{messages('basic-13.key254')/*差旅申请结束日期后*/}&nbsp;
                          <InputNumber defaultValue={info.id && paramsData.remindDay} min={1} max={999} precision={0} placeholder={messages('basic-13.key140')/*请输入temp1*/}
                          onChange={value => onChange({ remindDay: value })}/>
                          {messages('basic-13.key255')/*天*/
                          }
                        </Col>
                        <Col span={10}>
                          {messages('basic-13.key139')/*发送时间*/}:&nbsp;
                          <Select placeholder={messages('common.select')/*请选择*/}
                                  onChange={ value => onChange({ hour: value }) }
                                  style={{display: 'inline-block', width: '50%'}}
                                  defaultValue={ info.id && info.hour + ":00"}>
                            {hourOption}
                          </Select>
                        </Col>
                      </Row>
                    )}
                  </WrapFormItem>
                )}
            </FormItem>
            <FormItem
              label={messages('basic-13.key34')/*提醒方式*/}
              {...formItemLayout} className="checkbox-item"
            >
              {getFieldDecorator('remindTypes', {
                rules: [{
                  required: true,
                  message: messages('common.can.not.be.empty',{arg1: messages('basic-13.key34')/*提醒方式*/})/*{arg1} 不能为空*/
                }],
                initialValue: info.id ? paramsData.remindTypes : null
              })(
                <CheckboxGroup options={remindTypesOption}/>
              )}
            </FormItem>
            <h3 className='sub-title'>{messages('basic-13.key224')/*附加规则*/}</h3>
            <FormItem
              label={messages('basic-13.key242')/*信用规则*/}
              {...formItemLayout}>
              {honestLoading ? <Spin size="small" /> : (
                getFieldDecorator('conditionId', {
                  initialValue: honestInfo.id ? [{ id: honestInfo.id, ruleCondition: honestInfo.ruleCondition }] : undefined
                })(
                  <Chooser
                    placeholder={messages('common.select')/*请选择*/}
                    type="beer-honest"
                    single
                    valueKey="id"
                    labelKey="ruleCondition"
                    disabled={!(priority && priority.levelOrgId)}
                    listExtraParams={honestExtraParams}
                  />
                )
              )}
            </FormItem>
          </Form>
        </Spin>
        <div className='slide-footer'>
          <Button type='primary' onClick={this.handleSave} loading={saveLoading}>{messages('common.ok')/*确定*/}</Button>
          <Button onClick={() => this.props.close()}>{messages('common.back')/*返回*/}</Button>
        </div>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    company: state.login.company
  }
}

export default TravelContent
